import saleOrdersAPI from '../../../common/api/breedsales/orderbills.api.js';
import doT from '../../../../vendor/template/doT.js';
import { auditStateToHtml } from "../../../common/json-mapping/state-content-mapping.js";
import watermark from '../../../common/watermark.js';
import { Collaboration_APP, TEST_NUMBER, YY_NUMBER } from '../../../../../public/js/config/config.js';

(function (window, document, $) {
    const salesplanmainTemplate = doT.template($('#salesplanmain-template').text());
    let _vm, _res, operatarr = [], index, resTotal = [], listindex = "", getMainMessage = [], getMainInfo = [];
    let _page = {
        pageSize: 10,
        pageIndex: 0,
        totalPages: -1,
    }
    $(function () {
        window.sessionStorage.removeItem('getEntryInfo')
        window.sessionStorage.removeItem('mainInfo')
        _vm = new Vue({
            el: "#salesplanmain",
            data() {
                return {
                    salesplanList: [],
                    page: { ..._page }
                }
            },
            computed: {
                rgb() {
                    return `111`
                }
            }
        });
        _initCommand();
        _search();
        _initSlide();
        _ctlReturn();
        pullLoad();
        _returnMain();
        liststatues();
        _watermarkBgImg();
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
    });

    //TODO : 命名初始化
    const _initCommand = () => {
        // 新增按钮
        $('#addsaleorders').on('click', function (e) {
            JSON.stringify(Utils.SetSessionStorage("getMainMessage", getMainMessage))
            location.href = `../saleorders/addsaleorders.html?v=${Utils.GetTime()}`;
        });
        // 显示功能可视区
        $(document).on('click', '.ellipsis', function (e) {
            $(document).off("click", ".looksale")
            e.stopPropagation()
            $(".saleElp").siblings('.detail').css('display', 'none')
            $(this).parents(".salesplanstate").siblings('.detail').css('display', 'block')
            index = $(this).parents('.looksale').index()
            let billindex = resTotal[index].billStatus
            let $opration = $(this).parents('.saleElp').siblings('.detail')
            // 已保存
            if (billindex === 1) {
                $opration.find('.savesale').css('display', 'none')
                $opration.find('.settle').css('display', 'none')
            }
            // 已提交
            if (billindex === 2) {
                $opration.find('.subsale').css('display', 'none')
                $opration.find('.settle').css('display', 'none')
            }
            // 已审核
            if (billindex === 3) {
                $opration.find('.antiaudit').siblings().css('display', 'none')
                $opration.find('.viewdetails').css('display', 'block')
                $opration.find('.auditsettle').css('display', 'block')
            }
            //已结算完
            if (billindex === 21) {
                $opration.find('.savesale').css('display', 'none')
                $opration.find('.subsale').css('display', 'none')
                $opration.find('.auditsettle').css('display', 'none')
            }
        })
        // 点击功能可视区之外的区域
        $(document).bind("click", function (e) {
            var target = $(e.target);
            if (target.closest(".saleElp").length == 0) { //点击可视区域.saleElp之外的地方触发
                $(".saleElp").siblings('.detail').css('display', 'none')
            }
            // 点击整行跳转详情页面
            $(document).on('click', '.looksale', function (e) {
                $(document).off("click", ".looksale")
                index = $(this).index()
                let isAdvance = $(this).attr('data-isAdvance');
                location.href = `../saleorders/detailssaleorders.html?v=${Utils.GetTime()}&id=${resTotal[index].id}&isAdvance=${isAdvance}`;
            })
        })
        // 点击整行跳转详情页面
        $(document).on('click', '.looksale', function (e) {
            e.stopPropagation()
            $(document).off("click", ".looksale")
            index = $(this).index()
            let isAdvance = $(this).attr('data-isAdvance');
            location.href = `../saleorders/detailssaleorders.html?v=${Utils.GetTime()}&id=${resTotal[index].id}&isAdvance=${isAdvance}`;
        });

        //预收款按钮事件
        $(document).on('click', '.payment-orders', function (e) {
            e.stopPropagation()
            getMainInfo = [];
            index = $(this).index();
            let id = $(this).attr('data-id');
            let isAdvance = $(this).attr('data-isAdvance');
            let orgName = $(this).attr('data-orgName');
            let custName = $(this).attr('data-custName');
            let custNumCode = $(this).attr('data-custNumCode');
            let salePerName = $(this).attr('data-salePerName');
            let salePerNumCode = $(this).attr('data-salePerNumCode');
            let totalCount = $(this).attr('data-totalCount');
            let totalPrice = $(this).attr('data-totalPrice');
            let bizDate = $(this).attr('data-bizDate');
            let info = {
                orgName: orgName, custName: custName, custNumCode: custNumCode, salePerName: salePerName, salePerNumCode: salePerNumCode,
                totalCount: totalCount, totalPrice: totalPrice, bizDate: bizDate
            }
            getMainInfo.push(info)
            JSON.stringify(Utils.SetSessionStorage("getMainInfo", getMainInfo))
            location.href = `../saleorders/paymentorders.html?v=${Utils.GetTime()}&id=${id}&isAdvance=${isAdvance}`;
        });

        // 操作
        $(document).on('click', '.saledetail li:not(.operation)', function (e) {
            e.stopPropagation()
            index = $(this).parents('.looksale').index()
            let operat = $(this).index()
            operatsales(resTotal[index].id, operat)
            $(this).parents('.detail').css('display', 'none')
        });

        // 查看详情
        $(document).on('click', '.viewdetails', function (e) {
            e.stopPropagation()
            index = $(this).parents('.looksale').index()
            $(this).parents('.detail').css('display', 'none')
            let isAdvance = $(this).attr('data-isAdvance');
            location.href = `../saleorders/detailssaleorders.html?v=${Utils.GetTime()}&id=${resTotal[index].id}&isAdvance=${isAdvance}`;
        })
        // 编辑
        $(document).on('click', '.edit', function (e) {
            e.stopPropagation()
            JSON.stringify(Utils.SetSessionStorage("getMainMessage", getMainMessage))
            index = $(this).parents('.looksale').index()
            $(this).parents('.detail').css('display', 'none')
            location.href = `../saleorders/addsaleorders.html?v=${Utils.GetTime()}&id=${resTotal[index].id}`;
        });
    }
    // 提示
    const operatsales = (id, operat) => {
        $.modal({
            autoClose: false,
            title: `${operatarr[operat]}提示`,
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div  style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认${operatarr[operat]}<span style="color:red">[${resTotal[index].billNo}]</span>单据？该操作无法撤销！</div>
					</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "确定", onClick: function () {
                        _initPage()
                        switch (operatarr[operat]) {
                            case '删除':
                                saleOrdersAPI.delSalesList(id).then(res => {
                                    _initDataTable();
                                    $.toptip('删除成功。', 'success');
                                    $.closeModal()
                                })
                                break;   //找到之后，退出循环，不再执行下面的语句
                            case '提交':
                                saleOrdersAPI.submitSales(id).then(res => {
                                    _initDataTable();
                                    $.toptip('提交成功。', 'success');
                                    $.closeModal()
                                })
                                break;
                            case '反提交':
                                saleOrdersAPI.unsubmitSales(id).then(res => {
                                    _initDataTable();
                                    $.toptip('反提交成功。', 'success');
                                    $.closeModal()
                                }).catch(() => {
                                    _initDataTable();
                                    $.closeModal();
                                })
                                break;
                            case '审核':
                                saleOrdersAPI.auditSales(id).then(res => {
                                    _initDataTable();
                                    $.toptip('审核成功。', 'success');
                                    $.closeModal()
                                }).catch(() => {
                                    _initDataTable();
                                    $.closeModal();
                                })
                                break;
                            case '反审核':
                                saleOrdersAPI.antiauditSales(id).then(res => {
                                    _initDataTable();
                                    $.toptip('反审核成功。', 'success');
                                    $.closeModal()
                                }).catch(() => {
                                    _initDataTable();
                                    $.closeModal();
                                })
                                break;
                            case '反结算':
                                saleOrdersAPI.putRollSettle(id).then(res => {
                                    _initDataTable();
                                    $.toptip('反结算成功。', 'success');
                                    $.closeModal()
                                }).catch(() => {
                                    _initDataTable();
                                    $.closeModal();
                                })
                                break;
                            case '结算':
                                saleOrdersAPI.putAuditSettle(id).then(res => {
                                    _initDataTable();
                                    $.toptip('结算成功。', 'success');
                                    $.closeModal()
                                }).catch(() => {
                                    _initDataTable();
                                    $.closeModal();
                                })
                                break;
                        }

                    }
                }
            ]
        });
    }

    // 搜索
    const _search = () => {
        // 表单提交
        $("#search_bar form").submit(function () {
            _initPage()
            _initDataTable();
            return false;
        });
        // 搜索框为空
        if (!Utils.IsNotNull($('#search-index').val())) {
            _initPage()
            _initDataTable()
        }
        // 取消搜索
        $('#search_cancel').on('click', function () {
            $('#search-index').val('')
            _initPage()
            _initDataTable()
        })
        // *
        $('#search_clear').on('click', function () {
            $('#search-index').val('')
            _initPage()
            _initDataTable()
        })
    }
    // 导航栏
    const liststatues = () => {
        $('#spleplan-navbar a').on('click', function () {
            listindex = Number($(this).index());
            $(this).addClass('weui-bar__item--on').siblings().removeClass('weui-bar__item--on');
            if (listindex === 0) {
                listindex = ""
            } else if (listindex === 4) {
                listindex=21
            }
            _initPage()
            _initDataTable()
        });
    }
    // 请求列表数据
    const _initDataTable = async () => {
        let personOrgs = await saleOrdersAPI.postUserOrgsList();
        let _personOrg = [];
        personOrgs.forEach(item => {
            if (item.optTag == 1 && item.tags.indexOf('210') !== -1) {
                _personOrg.push(item.oId);
            }
        });

        let _data = _vm.page;
        saleOrdersAPI.seachEmployees(Object.assign({
            orgId: "",
            searchInfo: $('#search-index').val(),
            billStatus: listindex,
            startDate: "",
            endDate: "",
            fitlerOrgs: _personOrg
        }, _data)).then(res => {
            _page = {
                pageSize: 10,
                pageIndex: _data.pageIndex + 1,
                totalPages: res.totalPages
            }
            _vm._data.page = Object.assign({}, _page);
            _res = res.items
            resTotal.push(..._res)
            _res.forEach(ele => {
                let confirm = []
                ele.billStatusCh = auditStateToHtml(ele.billStatus)
                if (ele.billStatus == 2) {
                    ele.entries.forEach(item => {
                        if (item.count == null) {
                            confirm.push(item.count)
                        }
                    });
                }
                ele.confirmNum = confirm.length;
            });
            _vm.salesplanList = []
            _vm.salesplanList = [..._vm.salesplanList, ...resTotal];
            $('.looksale:last').css('margin-bottom', '10px')
            $('#salesplantel').empty().append(salesplanmainTemplate(_vm.salesplanList));
            $('.looksale').eq(0).find('.saledetail').each(function (index, domele) {
                operatarr = $(domele).text().trim().split(' ')
            })
            $('.looksale:last').css('margin-bottom', '120px')
        });
    }

    // 下拉加载
    const _initSlide = () => {
        //分别设置滑动距离，开始位置，结束位置，和模拟数据的定时器
        let disY, startY, endY, timer, t, pullheight;
        // 触摸开始
        $('#salesplantel').on('touchstart', function (e) {
            startY = e.originalEvent.changedTouches[0].pageY;//开始时的坐标
        });
        // 移动中
        $('#salesplantel').on('touchmove', function (e) {
            $(".saleElp").siblings('.detail').css('display', 'none')
            // 点击整行跳转详情页面
            $(document).on('click', '.looksale', function (e) {
                $(document).off("click", ".looksale")
                index = $(this).index()
                let isAdvance = $(this).attr('data-isAdvance');
                location.href = `../saleorders/detailssaleorders.html?v=${Utils.GetTime()}&id=${resTotal[index].id}&isAdvance=${isAdvance}`;
            });
            endY = e.originalEvent.changedTouches[0].pageY;
            disY = endY - startY;//移动后的坐标减去开始坐标，滑动距离。
            if (isTop() && disY > 0) {
                e.preventDefault();
            }
            if (disY < 60) {
                $('#pull-down').css({
                    height: disY + 'px'//父盒子的高度随着滑动距离变化，有最大值。
                });
            } else {
                $('#pull-down').css({
                    height: 60 + 'px'//父盒子的最大高度
                });
            }
            // 结束时
            $('#salesplantel').on('touchend', function (e) {
                clearInterval(timer);
                endY = e.originalEvent.changedTouches[0].pageY;
                disY = endY - startY;
                if (isTop() && disY > 0) {
                    timer = setInterval(function () {
                        $('#pull-down').css({
                            height: 0 + 'px',//松手后的返回。
                        });
                        clearInterval(timer);
                        _initPage()
                        _initDataTable();//加载数据 
                    }, 300)
                } else {
                    $('#pull-down').css({
                        height: 0 + 'px',//松手后的返回。
                    });
                }
                $('#salesplantel').off('touchend')
            })
        });
    }
    const isTop = () => {
        var t = document.documentElement.scrollTop || document.body.scrollTop;
        return t === 0 ? true : false;
    }

    //TODO : 上拉加载
    const pullLoad = () => {
        // 监听滚动的父容器
        $("body").infinite().on("infinite", function () {
            let _data = _vm._data.page;
            if (_data.pageIndex == _data.totalPages) return;
            let self = this;
            if (self.loading) return;
            self.loading = true;
            setTimeout(function () {
                _initDataTable();
                self.loading = false;
            }, 500);   //模拟延迟
        });
    }
    // 控制返回按钮，返回的页面
    const _ctlReturn = () => {
        if (window.history && window.history.pushState) {
            history.pushState(null, null, document.URL);
            window.addEventListener('popstate', function () {
                history.pushState(null, null, document.URL);
                //跳转列表
                this.window.location = `../../main.html`;
            });
        }
    }
    //返回首页
    const _returnMain = () => {
        $('#returnMain').on('click', function () {
            location.href = '../../main.html'
        });
    }

    // 初始化分页
    const _initPage = () => {
        resTotal = []
        _page = {
            pageSize: 10,
            pageIndex: 0,
            totalPages: -1,
        }
        _vm._data.page = Object.assign({}, _page);
    }

    //添加水印信息
    const _watermarkBgImg = () => {
        let _userInfo = JSON.parse(Utils.GetSessionStorage("SNAccountEply")) || {};
        watermark.set(_userInfo.name + _userInfo.numCode);// 水印
        //saleOrdersAPI.queryUserName(Utils.GetQueryString('state') || YY_NUMBER.sourceID).then(res => {
        //    watermark.set(_userInfo.un + res.code);// 水印
        //}).catch(_ => {
        //    watermark.set(_userInfo.un);// 水印
        //});
    }

})(window, document, jQuery)